import Taro from '@tarojs/taro'
import { View, Input, Picker, Button } from '@tarojs/components'

import ListItem from '../../components/listItem'
import { addMember, getLevelList } from '../../api/myMember'
import { showToast, isPhone, isName, setUpdatePage } from '../../utils'

import './index.less'

class AddMember extends Taro.Component {
  config = {
    navigationBarTitleText: '新增'
  }

  state = {
    selectors: {
      gender: ['请选择', '男', '女'],
      genderKeys: ['', 1, 2],
      level: [],
      levelKeys: []
    },
    form: {
      name: '',
      sex: '请选择',
      phone: '',
      levelId: '请选择'
    }
  }

  componentDidMount() {
    this.getLevelList()
  }

  getLevelList = async () => {
    const res = await getLevelList()
    
    this.setState({
      selectors: {
        ...this.state.selectors,
        level: ['请选择', ...res.data.map(item => item.levelName)],
        levelKeys: ['', ...res.data.map(item => item.aiCourseLevelId)]
      }
    })
  }

  onPickerChange = (key, name, ev) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: this.state.selectors[name][ev.detail.value]
      }
    })
  }

  formatForm = () => {
    const newForm = {}
    const { selectors, form } = this.state

    for (let key in form) {
      if (key === 'sex') {
        const index = selectors.gender.indexOf(this.state.form[key])
        newForm[key] = selectors.genderKeys[index]
      } else if (key === 'levelId') {
        const index = selectors.level.indexOf(this.state.form[key])
        newForm[key] = selectors.levelKeys[index]
      } else {
        newForm[key] = form[key].trim()
      }
    }

    return newForm
  }

  addMember = async () => {
    const form = this.formatForm()
    
    for (let key in form) {
      if (form[key] === '') {
        switch(key) {
          case 'name':
            showToast('请填写姓名')
            return
          case 'sex':
            showToast('请选择性别')
            return
          case 'phone':
            showToast('请填写手机号')
            return
        }
      }
    }

    if (!isName(form.name)) {
      showToast('姓名格式有误')
      return
    }

    if (!isPhone(form.phone)) {
      showToast('手机号有误')
      return
    }

    Taro.showLoading()

    const res = await addMember(form)

    Taro.hideLoading()

    if (res.code === 1) {
      showToast('新增成功！')

      setUpdatePage(2)
      Taro.navigateBack()
    } else {
      showToast(res.message)
    }
  }

  handleInput = (key, ev) => {
    this.setState({
      form: {
        ...this.state.form,
        [key]: ev.target.value
      }
    })
  }

  render() {
    const { form, selectors } = this.state

    return (
      <View className="page">
        <View className="partner-list">
          <ListItem label="姓名" required border>
            <Input
              value={ form.name }
              type="text"
              placeholder="请填写"
              placeholderClass="placeholder"
              onInput={ this.handleInput.bind(this, 'name') }
            />
          </ListItem>
          <ListItem label="性别" required border>
            <Picker
              mode="selector"
              range={ selectors.gender }
              onChange={ this.onPickerChange.bind(this, 'sex', 'gender') }
            >
              { form.sex }
            </Picker>
          </ListItem>
          <ListItem label="手机号" required border>
            <Input
              value={ form.phone }
              type="number"
              placeholder="请填写"
              placeholderClass="placeholder"
              onInput={ this.handleInput.bind(this, 'phone') }
            />
          </ListItem>
          <ListItem label="级别">
            <Picker
              mode="selector"
              range={ selectors.level }
              onChange={ this.onPickerChange.bind(this, 'levelId', 'level') }
            >
              { form.levelId }
            </Picker>
          </ListItem>
          <Button hover-class="btn-active" className="add-btn" onClick={ this.addMember }>确定</Button>
        </View>
        <View className="be-careful">
          <View>注意：</View>
          <View>① 级别为非必填项，建议由学员自己通过水平测试进行定级。</View>
          <View>② 特殊原因，可由代理商帮其选择级别，一旦确定了级别，学员便无法在APP端自行更改，请谨慎操作。</View>
          <View>③ 学员级别在正式学习课程以后，如法修改。</View>
          <View>④ 如需修改会员信息，请联系平台工作人员。</View>
        </View>
      </View>
    )
  }
}

export default AddMember